package com.fzg.common.tool.builder;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * create by fzg
 * 2022/12/15 9:53
 */


public class Builder<T> {

    /**
     * 存储调用方 指定构造类的 构造器
     */
    private final Supplier<T> constructor;

    /**
     * 存储 指定类 所有需要初始化的属性
     */
    private final List<Consumer> dInject = new ArrayList<>();

    private Builder(Supplier<T> constructor){
        this.constructor = constructor;
    }

    public static <T> Builder<T> builder(Supplier<T> constructor){
        return new Builder<>(constructor);
    }

    public <P1> Builder<T> with(Builder.DinjectConsumer<T,P1> consumer,P1 p1){
        Consumer<T> c = instance ->consumer.accept(instance,p1);
        dInject.add(c);
        return this;
    }



    public T build(){
        //调用supplier 生成类示例
        T instance = constructor.get();
        //调用传入的setter方法，完成属性的初始化
        dInject.forEach(dInject -> dInject.accept(instance));
        //返回构造完成的类实例
        return instance;
    }

    @FunctionalInterface
    public interface DinjectConsumer<T,P1>{
        void accept(T t,P1 p1);
    }

}
